package com.suneee.trades.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.suneee.base.util.ContextHelper;
import com.suneee.context.page.Page;
import com.suneee.context.page.Sort;
import com.suneee.context.page.Sort.Order;
import com.suneee.core.util.StringUtils;
import com.suneee.orm.GenericDao;
import com.suneee.orm.util.WhereClauseBuilder;
import com.suneee.trades.bean.TradesInfoDTO;
import com.suneee.trades.dao.ViewShoppDao;
import com.suneee.trades.entity.ViewShopp;

@Repository("viewShoppDao")
public class ViewShoppDaoImpl extends GenericDao<ViewShopp, Integer>implements ViewShoppDao {

	@Override
	public Page<ViewShopp> selectWaitSendGoods(TradesInfoDTO dto) {
		List<Object> list = null;
		Integer adminId = ContextHelper.getCurrentLoginInfo().getAdminId();
		String entCode = ContextHelper.getCurrentLoginInfo().getEnterpriseCode();
		List<Map<String,Object>> shopList = this.queryForList("select shop_id from t_shop_admin where admin_id = ?", adminId);
		if(null != shopList && shopList.size() > 0)
		{
			list = new ArrayList<Object>();
			for(Map<String,Object> map :shopList)
			{
				list.add(map.get("shop_id"));
			}
		}
		if(null == shopList || shopList.size() == 0)
		{
			list = new ArrayList<Object>();
			list.add(" ");
		}
		WhereClauseBuilder wcb = new WhereClauseBuilder();
		wcb.equals("name", dto.getTitle());
		wcb.equals("shop_id",dto.getShopId());
		wcb.in("shop_id",list);
		wcb.equals("company_name",dto.getCompanyName());
		wcb.equals("buyer_nick",dto.getBuyerNick());
		wcb.contains("tids",dto.getTid());
		wcb.equals("enterprise_code",dto.getEnterpriseCode());
		wcb.between("created", dto.getCreateStartTime(), dto.getCreateEndTime());
		wcb.between("audit_time", dto.getReviewStartTime(), dto.getReviewEndTime());
		wcb.equals("company_code",dto.getCompanyCode());
		
		wcb.in("status", dto.getSendStatus());
	   //若销售订单存在未关闭售后单则 在打单发货界面隐藏 dto.getSendStatus().size() > 1 表示的是查询待打单发货的数据 dto.getSendStatus().size() == 1表示查询已打单发货的数据。
		if(null != dto.getSendStatus() && dto.getSendStatus().size() > 1)
		{
			wcb.appendWhere("tid NOT IN (SELECT DISTINCT a.tid FROM t_trades_info a INNER JOIN t_refund_apply b ON a.tid = b.tid  WHERE a.enterprise_code = '"+ entCode.trim() +"' AND (b.process_status = 'INIT' OR process_status = 'PROCESS' )  AND b.after_sale_type IN ('REFUND_GOODS','REFUND_MONEY')) ");
			
		}
		
		
		wcb.equals("channel_code",dto.getChannelCode());
		
		dto.setPageNumber(dto.getPageNumber() == 0 ? 1 : dto.getPageNumber());
		dto.setPageSize(dto.getPageSize() == 0 ? 10 : dto.getPageSize());
		dto.setSort((dto.getSort() == null || StringUtils.isEmpty(dto.getSort().getOrderByClause()))
				? new Sort("shopp_id", Order.ASC) : dto.getSort());
		return this.selectWhere(wcb.getSql(),dto, wcb.getArgs());
		
	}
}
